<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:insert="~{include :: header('编辑需求')}" />
	<th:block th:insert="~{include :: summernote-css}" />
	<th:block th:insert="~{include :: datetimepicker-css}" />
	<th:block th:insert="~{include :: bootstrap-fileinput-css}" />
	<th:block th:insert="~{include :: select2-css}" />
	<style>
		fieldset {
		    border: 1px solid #d0d7de;
		    margin: 0;
		    min-width: inherit;
		}	
		legend {
		    display: block;
		    unicode-bidi: isolate;
		    padding-inline: 2px;
		}	
	</style>
</head>
<body>
    <div class="main-content">
        <form id="form-issue-add" class="form-horizontal" th:object="${issueInfo}">
			<input name="id"  type="hidden"  th:field="*{id}" />
            <h4 class="form-header h4">编辑需求</h4>
			<fieldset class="tabular">
				<legend>修改属性</legend>
				<div id="all_attributes">
					<div class="row">
						<div class="col-sm-10">
					        <div class="form-group">
					            <label class="col-sm-2 control-label is-required">项目</label>
					            <div class="col-sm-6">
									<select id="projectId" name="projectId" class="form-control" required>
									    <option th:each="project : ${projectList}" th:text="${project['name']}" th:value="${project['id']}" th:field="*{projectId}"></option>
									</select>
					            </div>
					        </div>
					    </div>
					</div>
					<div class="row">
						<div class="col-sm-10">
					        <div class="form-group">
					            <label class="col-sm-2 control-label is-required">跟踪</label>
					            <div class="col-sm-6">
									<select id="trackerId" name="trackerId" class="form-control" required>
									    <option th:each="tracker : ${trackerList}" th:text="${tracker['name']}" th:value="${tracker['id']}" th:field="*{trackerId}"></option>
									</select>
					            </div>
					        </div>
					    </div>
					</div>
		            <div class="row">
		                <div class="col-sm-10">
		                    <div class="form-group">
		                        <label class="col-sm-2 control-label is-required">主题</label>
		                        <div class="col-sm-10">
		                            <input id="subject" name="subject" class="form-control" type="text" size="80" maxlength="255" th:field="*{subject}" required>
		                        </div>
		                    </div>
		                </div>
		            </div>
		            <div class="row">
		                <div class="col-sm-10">
		                    <div class="form-group">
		                        <label class="col-sm-2 control-label">描述</label>
		                        <div class="col-sm-10">
									<div class="ibox-content no-padding" id="issue_description_and_toolbar" style="display:none;">
									    <div class="summernote" id="project_description" th:utext="*{description}"></div>
									</div>
									<a style="line-height: 30px;" href="javascript:void(0);" onclick="$(this).hide(); $('#issue_description_and_toolbar').show(); return false;"><i class="fa fa-pencil"> </i> 编辑</a>
		                        </div>
		                    </div>
		                </div>
		            </div>
		            <div class="row">
						<div class="col-sm-10">
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label is-required">状态</label>
							        <div class="col-sm-8">
										<select id="statusId" name="statusId" class="form-control">
										    <option th:each="issueStatuse : ${issueStatuseList}" th:text="${issueStatuse['name']}" th:value="${issueStatuse['id']}" th:field="*{statusId}"></option>
										</select>
							        </div>
							    </div>
							</div>
							<!--
								
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">父任务：</label>
							        <div class="col-sm-8">
										<div class="input-group">
											<input name="deptName" onclick="selectDeptTree()" id="treeName" type="text" class="form-control">
										    <span class="input-group-addon"><i class="fa fa-search"></i></span>
										</div>
							        </div>
							    </div>
							</div>
							-->
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">开始日期</label>
							        <div class="col-sm-6">
										<div class="input-group date">
										    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
										    <input type="text" class="form-control" name="startDate" id="startDate" placeholder="yyyy-MM-dd" th:field="*{startDate}">
										</div>
							        </div>
							    </div>
							</div>
						</div>
		            </div>
					<div class="row">
						<div class="col-sm-10">
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label is-required">优先级</label>
							        <div class="col-sm-8">
										<select id="priorityId" name="priorityId" class="form-control" >	
											<option th:each="issuePrioritie : ${issuePrioritieList}" th:text="${issuePrioritie['name']}" th:value="${issuePrioritie['id']}" th:field="*{priorityId}"></option>
										</select>
							        </div>
							    </div>
							</div>
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">计划完成日期</label>
							        <div class="col-sm-6">
										<div class="input-group date">
										    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
										    <input type="text" class="form-control" name="dueDate" id="dueDate" placeholder="yyyy-MM-dd" th:field="*{dueDate}">
										</div>
							        </div>
							    </div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-sm-10">
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">指派给</label>
							        <div class="col-sm-8">
										<select id="assignedToId" name="assignedToId" class="form-control" >			
											<option value="0" th:field="*{assignedToId}">&emsp;</option>
											<option th:each="user : ${userList}" th:text="${user['userName']}" th:value="${user['userId']}" th:field="*{assignedToId}"></option>
										</select>
							        </div>
							    </div>
							</div>
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">预计时间</label>
							        <div class="col-sm-5">
										<input id="estimatedHours" name="estimatedHours" placeholder="h:mm" class="form-control" type="text" maxlength="11" th:field="*{estimatedHours}">
							        </div>
									<label style="padding-top: 8px;">小时</label>
							    </div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-sm-10">
					<div class="col-sm-6">
					    <div class="form-group">
					        <label class="col-sm-4 control-label">类别</label>
					        <div class="col-sm-7">
								<select id="categoryId" name="categoryId" class="form-control">
									<option value="0">&emsp;</option>
								    <option th:each="issueCategorie : ${issueCategorieList}" th:text="${issueCategorie['name']}" th:value="${issueCategorie['id']}" th:field="*{categoryId}"></option>
								</select>
					        </div>
							<div style="padding-top: 2px;">
								<i class="fa fa-plus-circle fa-2x" style="cursor: pointer;" onclick="openAddCategoryModal()"></i>
							</div>
					    </div>
					</div>
							<div class="col-sm-6">
							    <div class="form-group">
							        <label class="col-sm-4 control-label">% 进度</label>
							        <div class="col-sm-6">							
										<select name="doneRatio" id="doneRatio" class="form-control">
											<option value="0" th:field="*{doneRatio}">0 %</option>
											<option value="10" th:field="*{doneRatio}">10 %</option>
											<option value="20" th:field="*{doneRatio}">20 %</option>
											<option value="30" th:field="*{doneRatio}">30 %</option>
											<option value="40" th:field="*{doneRatio}">40 %</option>
											<option value="50" th:field="*{doneRatio}">50 %</option>
											<option value="60" th:field="*{doneRatio}">60 %</option>
											<option value="70" th:field="*{doneRatio}">70 %</option>
											<option value="80" th:field="*{doneRatio}">80 %</option>
											<option value="90" th:field="*{doneRatio}">90 %</option>
											<option value="100" th:field="*{doneRatio}">100 %</option>
										</select>
							        </div>
							    </div>
							</div>
						</div>
					</div>
				</div>
			</fieldset>

			<fieldset>
				<legend>登记工时</legend>
			</fieldset>
			<fieldset>
				<legend>说明</legend>
				<div class="row">
				    <div class="col-sm-12">
						<div class="ibox-content no-padding">
						    <div class="summernote" id="issue_notes"></div>
						</div>
				    </div>
				</div>
			</fieldset>
			<fieldset>
				<legend>文件</legend>
				<div class="row">
				    <div class="col-sm-12">
					    <div class="file-loading">
					        <input id="multipleFile" name="files" type="file" multiple>
					    </div>
				    </div>
				</div>
			</fieldset>
        </form>
    </div>
    <div class="row" th:if="${buttonShow} != 1">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
        </div>
    </div>
	<th:block th:insert="~{include :: footer}" />
	<th:block th:insert="~{include :: summernote-js}" />
	<th:block th:insert="~{include :: datetimepicker-js}" />
	<th:block th:insert="~{include :: bootstrap-fileinput-js}" />
	<th:block th:insert="~{include :: select2-js}" />
	<script th:src="@{/js/upload.js}"></script>
	<script>
	    var prefix = ctx + "project/issue";
		// 存储上传的文件信息
		var uploadedFiles = [];
		
		// 打开添加类别弹窗
		function openAddCategoryModal() {
			var projectId = $("#projectId").val();
		    var categoryUrl = ctx + "system/categorie/add?projectId=" + projectId;
		    $.modal.open("添加类别", categoryUrl, '600', '400');
		}
		
		// 刷新类别下拉框
		function refreshCategoryDropdown() {
			var projectId = $("#projectId").val();
			if (projectId) {
				$.ajax({
					url: prefix + "/categories/" + projectId,
					type: "GET",
					success: function(result) {
						if (result.code == 0) {
							var categorySelect = $("#categoryId");
							var currentValue = categorySelect.val();
							categorySelect.empty();
							categorySelect.append('<option value="0">&emsp;</option>');
							
							if (result.data && result.data.length > 0) {
								$.each(result.data, function(index, category) {
									categorySelect.append('<option value="' + category.id + '">' + category.name + '</option>');
								});
							}
							// 恢复之前选中的值
							if (currentValue) {
								categorySelect.val(currentValue);
							}
							$.modal.msgSuccess("类别列表已刷新");
						}
					},
					error: function() {
						$.modal.alertError("刷新类别列表失败");
					}
				});
			}
		}
		
		$(document).ready(function () {
		    $('.summernote').summernote({
		        lang: 'zh-CN',
				height: 240
		    });
			
			// 多图上传
			$("#multipleFile").fileinput({
			    uploadUrl: ctx + 'common/uploads',
			    uploadAsync: true,
				showClose: false,
				showUpload: false
			}).on('filebatchselected', function(event, files) {
    // 文件被选择后，自动触发上传 [1,4](@ref)
				$(this).fileinput("upload");
			}).on('fileremoved', function (event, id, index) {
			    $("input[name='" + event.currentTarget.id + "']").val('')
				// 从uploadedFiles数组中删除对应的文件信息
				if (uploadedFiles.length > 0 && index >= 0 && index < uploadedFiles.length) {
				    uploadedFiles.splice(index, 1);
				}
			}).on('fileuploaded', function(event, data, previewId, index) {
				// 文件上传成功后的回调函数
				var rsp = data.response;
				if (rsp) {
					log.info("return urls：" + rsp.urls)
					log.info("reutrn fileNames：" + rsp.fileNames)
					log.info("reutrn newFileNames：" + rsp.newFileNames)
					log.info("return originalFilenames：" + rsp.originalFilenames)
					log.info("return fileSize：" + rsp.fileSize)

					// 保存上传的文件信息
					if (rsp.urls && rsp.fileNames && rsp.newFileNames && rsp.originalFilenames && rsp.fileSize) {
						uploadedFiles.push({
							url: rsp.urls,
							filename: rsp.fileNames,
							diskFilename: rsp.newFileNames,
							originalFilename: rsp.originalFilenames,
							fileSize: rsp.fileSize
						});
					}
				} else {
					console.log("文件上传响应为空");
				}
			});
		});

		$(function() {
			// 初始化table配置以便使用detailTab方法
			var options = {
				detailUrl: prefix + "/{id}",
				modalName: "需求详情"
			};
			$.table.init(options);
			layui.use('laydate', function(){
			    var laydate = layui.laydate;
				// 获取输入框的当前值作为默认值
				var startDateValue = $('#startDate').val();
				laydate.render({ 
					elem: '#startDate',
					type: 'date'					,
					value: startDateValue || new Date()
				});
				laydate.render({ 
					elem: '#dueDate',
					type: 'date'
				});
				laydate.render({ 
					elem: '#serverExpirDate',
					type: 'date'
				});
		  	});
		})
		
		function submitHandler(){
			if ($.validate.form()) {
				// 验证预计时间格式
				var estimatedHours = $('#estimatedHours').val().trim();
				if (estimatedHours !== '') {
					var pattern = /^\d+(:\d{1,2})?$/;
					if (!pattern.test(estimatedHours)) {
						$.modal.alertWarning('预计时间格式不正确');
						return false;
					}
				}
				
				var descriptionHTML = $('#project_description').summernote('code');
				var description = '';
				// 检查是否为空内容（去除HTML标签后检查）
				var descriptionContent = descriptionHTML.replace(/<[^>]*>/g, '').trim();
				if (descriptionContent === '' || descriptionHTML === '<p><br></p>' || descriptionHTML === '<p></p>') {
					description = '';
				} else {
					// 处理base64图片
					processBase64Images(descriptionHTML, function(processedHTML) {
						description = processedHTML;
					});
				}
				
				var notesHTML = $('#issue_notes').summernote('code');
				var notes = '';
				// 检查是否为空内容（去除HTML标签后检查）
				var notesContent = notesHTML.replace(/<[^>]*>/g, '').trim();
				if (notesContent === '' || notesHTML === '<p><br></p>' || notesHTML === '<p></p>') {
					notes = '';
				} else {
					// 处理base64图片
					processBase64Images(notesHTML, function(processedHTML) {
						notes = processedHTML;
					});
				}
				
				
				var data = $('#form-issue-add').serializeArray();
				var issueId = $('input[name="id"]').val();
				data.push({"name": "description", "value": description});
				data.push({"name": "notes", "value": notes});
				data.push({"name": "uploadedFiles", "value": JSON.stringify(uploadedFiles)});
				console.log("提交数据:", JSON.stringify(data))

				var topWindow = $(window.parent.document);
				var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
				if(currentId == prefix + "/index"){
					console.log("currentId" + currentId);
					$.modal.loading("数据加载中");
				}else {
					window.parent.$.modal.loading("数据加载中");
				}

				$.operate.save(prefix + "/edit", data, function(result){
					console.log("保存后跳转");					
					if(currentId != prefix + "/index"){
						$.modal.openTab("需求详情", prefix + "/" + issueId, true);
					}
				});
			}
		}
    </script>
</body>
</html>